package hos.ui.edit;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.ListAdapter;

import hos.ui.R;

/**
 * <p>Title: IconAutoCompleteTextView </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2023/6/9 16:46
 */
public class IconAutoCompleteTextView extends AutoCompleteTextView implements View.OnTouchListener, View.OnFocusChangeListener {

    private boolean mPasswrodShow = true;
    /**
     * 后缀图标
     */
    private Drawable mSuffixDrawable;
    /**
     * 前缀图标
     */
    private Drawable mPrefixDrawable;

    private View.OnTouchListener mOnTouchListener;

    private View.OnClickListener mOnSuffixIconClickListener;

    private View.OnClickListener mOnPrefixIconClickListener;

    private View.OnFocusChangeListener mOnFocusChangeListener;

    private int iconType;

    public IconAutoCompleteTextView(Context context) {
        this(context, null);
    }

    public IconAutoCompleteTextView(Context context, AttributeSet attrs) {
        this(context, attrs, android.R.attr.editTextStyle);
    }

    public IconAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.IconAutoCompleteTextView, defStyleAttr, 0);
        try {
            // 处理后缀图标
            int cdId = typedArray.getResourceId(R.styleable.IconAutoCompleteTextView_suffixIcon, -1);
            if (cdId == -1) {
                cdId = typedArray.getInt(R.styleable.IconAutoCompleteTextView_suffixIcon, -1);
            }
            iconType = typedArray.getInteger(R.styleable.IconAutoCompleteTextView_suffixIconType, 0);
            if (iconType == 0) {
                // 清空按钮
                if (cdId == -1) {
                    Drawable drawable = typedArray.getDrawable(R.styleable.IconAutoCompleteTextView_suffixIcon);
                    if (drawable == null) {
                        cdId = R.drawable.ic_baseline_close_24;
                        setSuffixIcon(cdId);
                        setSuffixVisible(mSuffixDrawable, false);
                    } else {
                        setSuffixIcon(drawable);
                        setSuffixVisible(drawable, false);
                    }
                } else {
                    setSuffixIcon(cdId);
                    setSuffixVisible(mSuffixDrawable, false);
                }
                if (cdId == R.drawable.ic_baseline_close_24) {
                    setTint(mSuffixDrawable, getCurrentHintTextColor());
                }
            } else if (iconType == 2) {
                // 密码
                setSuffixIcon(R.drawable.baseline_visibility_24);
                setInputType((getInputType() & ~(EditorInfo.TYPE_MASK_VARIATION))
                        | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
                // 隐藏密码
                setTransformationMethod(PasswordTransformationMethod.getInstance());
                mPasswrodShow = false;
            } else {
                if (cdId != -1) {
                    setSuffixIcon(cdId);
                } else {
                    Drawable drawable = typedArray.getDrawable(R.styleable.IconAutoCompleteTextView_suffixIcon);
                    if (drawable != null) {
                        setSuffixIcon(drawable);
                    }
                }
            }
            // 前缀按钮
            int prefixId = typedArray.getResourceId(R.styleable.IconAutoCompleteTextView_prefixIcon, -1);
            if (prefixId == -1) {
                prefixId = typedArray.getInt(R.styleable.IconAutoCompleteTextView_prefixIcon, -1);
            }
            if (prefixId != -1) {
                setPrefixIcon(prefixId);
            } else {
                Drawable drawable = typedArray.getDrawable(R.styleable.IconAutoCompleteTextView_prefixIcon);
                if (drawable != null) {
                    setPrefixIcon(drawable);
                }
            }
            int editBackgroundType = typedArray.getInteger(R.styleable.IconAutoCompleteTextView_editBackgroundType, -1);
            IconEditText.setBackground(this,editBackgroundType);
        } finally {
            typedArray.recycle();
        }
        super.setOnFocusChangeListener(this);
        super.setOnTouchListener(this);
    }

    public void setIconType(int iconType) {
        this.iconType = iconType;
    }

    public void setSuffixIcon(Drawable src) {
        mSuffixDrawable = src;
        if (mSuffixDrawable == null) {
            return;
        }
        mSuffixDrawable.setBounds(0, 0, mSuffixDrawable.getIntrinsicWidth(), mSuffixDrawable.getIntrinsicHeight());
        final Drawable[] drawables = getCompoundDrawables();
        setCompoundDrawables(
                drawables[0],
                drawables[1],
                mSuffixDrawable,
                drawables[3]);
    }

    public void setSuffixIcon(int src) {
        setSuffixIcon(getDrawable(getContext(), src));
    }

    public void setPrefixIcon(Drawable src) {
        mPrefixDrawable = src;
        if (mPrefixDrawable == null) {
            return;
        }
        mPrefixDrawable.setBounds(0, 0, mPrefixDrawable.getIntrinsicWidth(), mPrefixDrawable.getIntrinsicHeight());
        final Drawable[] drawables = getCompoundDrawables();
        setCompoundDrawables(
                mPrefixDrawable,
                drawables[1],
                drawables[2],
                drawables[3]);
    }

    public void setPrefixIcon(int src) {
        setPrefixIcon(getDrawable(getContext(), src));
    }


    @Override
    public void setOnFocusChangeListener(final View.OnFocusChangeListener onFocusChangeListener) {
        mOnFocusChangeListener = onFocusChangeListener;
    }

    @Override
    public void setOnTouchListener(final View.OnTouchListener onTouchListener) {
        mOnTouchListener = onTouchListener;
    }

    public void setOnSuffixIconClickListener(OnClickListener iconClickListener) {
        this.mOnSuffixIconClickListener = iconClickListener;
    }

    public void setOnPrefixIconClickListener(OnClickListener iconClickListener) {
        this.mOnPrefixIconClickListener = iconClickListener;
    }

    private void setSuffixVisible(Drawable suffixDrawable, final boolean suffixVisible) {
        if (suffixDrawable == null) {
            return;
        }
        if (suffixDrawable.isVisible() == suffixVisible) {
            return;
        }
        suffixDrawable.setVisible(suffixVisible, false);
        final Drawable[] drawables = getCompoundDrawables();
        setCompoundDrawables(
                drawables[0],
                drawables[1],
                suffixVisible ? suffixDrawable : null,
                drawables[3]);
    }

    private void setPrefixVisible(Drawable prefixDrawable, final boolean prefixVisible) {
        if (prefixDrawable == null) {
            return;
        }
        if (prefixDrawable.isVisible() == prefixVisible) {
            return;
        }
        prefixDrawable.setVisible(prefixVisible, false);
        final Drawable[] drawables = getCompoundDrawables();
        setCompoundDrawables(
                prefixVisible ? prefixDrawable : null,
                drawables[1],
                drawables[2],
                drawables[3]);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        final int x = (int) motionEvent.getX();
        if (mSuffixDrawable != null && mSuffixDrawable.isVisible() && x > getWidth() - getPaddingRight() - mSuffixDrawable.getIntrinsicWidth()) {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if (iconType == 0) {
                    // 清空按钮
                    setText("");
                } else if (iconType == 2) {
                    // 隐藏或者显示密码
                    if (mPasswrodShow) {
                        mPasswrodShow = false;
                        // 隐藏密码
                        setTransformationMethod(PasswordTransformationMethod.getInstance());
                        setSuffixIcon(R.drawable.baseline_visibility_24);
                    } else {
                        mPasswrodShow = true;
                        // 显示密码
                        setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        setSuffixIcon(R.drawable.baseline_visibility_off_24);
                    }
                }
                if (mOnSuffixIconClickListener != null) {
                    mOnSuffixIconClickListener.onClick(view);
                }
            }
            return true;
        }
        if (mPrefixDrawable != null && mPrefixDrawable.isVisible() && x < mPrefixDrawable.getIntrinsicWidth()) {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if (mOnPrefixIconClickListener != null) {
                    mOnPrefixIconClickListener.onClick(view);
                }
            }
            return true;
        }
        return mOnTouchListener != null && mOnTouchListener.onTouch(view, motionEvent);
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        if (iconType == 0 && isFocused()) {
            setSuffixVisible(mSuffixDrawable, text.length() > 0);
        }
    }

    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (iconType == 0) {
            if (hasFocus && getText() != null) {
                setSuffixVisible(mSuffixDrawable, getText().length() > 0);
            } else {
                setSuffixVisible(mSuffixDrawable, false);
            }
        }
        ListAdapter adapter = getAdapter();
        if (adapter != null) {
            try {
                if (adapter.getCount() != 0) {
                    showDropDown();
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 这里数据是null
            }
        }
        if (mOnFocusChangeListener != null) {
            mOnFocusChangeListener.onFocusChange(view, hasFocus);
        }
    }

    /**
     * Specifies a tint for {@code drawable}.
     *
     * @param drawable The Drawable against which to invoke the method.
     * @param tint     Color to use for tinting this drawable
     */
    protected void setTint(Drawable drawable, int tint) {
        if (Build.VERSION.SDK_INT >= 21) {
            drawable.setTint(tint);
        }
    }

    private Drawable getDrawable(Context context, int id) {
        if (Build.VERSION.SDK_INT >= 21) {
            return context.getDrawable(id);
        }
        return context.getResources().getDrawable(id);
    }

    public void loadLonlat(){
        setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
    }

    public void clearListener() {
        mOnSuffixIconClickListener = null;
        mOnPrefixIconClickListener = null;
    }
}
